#!/bin/bash
# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#

echo "##########################"
echo "STARTING THE PTE CONTAINER"
echo "##########################"

TIMEOUT=120
waittime=5

function checkConfigFiles()
{
local rc=1
local starttime=$(date +%s)

while test "$(($(date +%s)-starttime))" -lt "$TIMEOUT" -a $rc -ne 0
do
    echo "Waiting for $waittime secs"
    sleep $waittime
    ls /var/hyperledger/fabric/pteconfig.tgz 2>/dev/null
    test $? -eq 0 && let rc=0
done
test $rc -ne 0 && echo "Oops ... Timed out and couldn't find the tx file , exiting" && exit 1
}

#Checking for config files needed for PTE
checkConfigFiles
tar -xzvf /var/hyperledger/fabric/pteconfig.tgz
#Copying the channel config txns
cp -r CITest/*.tx /var/hyperledger/fabric/artifacts/keyfiles/
cd $GOPATH/src/github.com/hyperledger/fabric-test/tools/PTE/CITest/scripts
CWD=$PWD/../Logs

{% if testcase != 'multihost' %}
{% for ch in channelnum %}
sed -i 's/\(\"channelTX\"\:\ \"\)\(.*\)/\1\/var\/hyperledger\/fabric\/artifacts\/keyfiles\/testorgschannel{{ ch }}.tx\"\,/g' ../{{ testcase }}/preconfig/channels/*chan{{ ch }}-create-TLS.json
{% if chaincode == 'samplejs' %}
sed -i 's/\(\"chaincodePath\"\:\ \"\)\(.*\)/\1\/root\/go\/src\/github.com\/hyperledger\/fabric-test\/chaincodes\/samplecc\/node"\,/g' ../{{ testcase }}/preconfig/{{ chaincode }}/{{ chaincode }}-chan{{ ch }}-install-TLS.json
{% endif %}
{% if chaincode == 'marbles02' %}
sed -i 's/\(\"metadataPath\"\:\ \"\)\(.*\)/\1\/root\/go\/src\/github.com\/hyperledger\/fabric-test\/fabric-samples\/chaincode\/marbles02\/go\/META-INF"\,/g' ../{{ testcase }}/preconfig/{{ chaincode }}/{{ chaincode }}-chan{{ ch }}-install-TLS.json
{% endif %}
{% endfor %}
{% endif %}
echo "#########################################"
echo "#          Starting Admin Tasks         #"
echo "#########################################"
{% if createChannel %}
echo "Creating Channel, Joining Peers to Channel"

./test_driver.sh -m {{ testcase }} -p
{% endif %}

echo "Installing and Instantiating the Chaincode"

./test_driver.sh -m {{ testcase }} -c {{ chaincode }}

echo "#########################################"
echo "#         Completed Admin Tasks         #"
echo "#########################################"
